<template>
  <picker :value="_value"
          selector-type='picker'
          :disabled="disabled"
          :range="options"
          :mode="mode"
          :start="start"
          :end="end"
          rangeKey="label"
          @change="change"
          class="picker"
          ref="pick">
    <view class="select-view"
          :class="{'text-placeholder':showValue===placeholder}">{{showValue}}
      <image src="/static/img/select_arrow.png" />
    </view>
  </picker>
</template>
<script>
// 不支持多级选择
export default {
  name: "SelectPicker",
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    mode: {
      type: String,
      default: "selector",
    },
    value: {},
    options: {
      type: Array,
      default: () => [],
    },
    start: {
      type: String,
      default: "",
    },
    end: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    setDefault: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    _value() {
      // let index = this.options.findIndex(o => o.value === this.value);
      // return index === -1 ? "" : index;
      return this.options.findIndex((o) => o.value === this.value);
    },
    range() {
      return this.options.map((o) => o.label);
    },
    rangeObj() {
      let obj = {};
      this.options.forEach((o) => {
        obj[o.value] = o.label;
      });
      return obj;
    },
    isSelect() {
      return this.mode === "selector";
    },
    showValue() {
      if (this.isSelect) {
        return this.rangeObj[this.value] || this.placeholder;
      } else {
        return this.value || this.placeholder;
      }
    },
  },
  created() {
    if (
      (this.value === "" || this.value === undefined) &&
      this.options.length &&
      this.setDefault
    ) {
      this.$emit("change", this.options[0].value);
    }
  },
  methods: {
    change(event) {
      let value = event.detail.value;
     
      if (this.isSelect) {
        if (value === -1) {
          value = 0;
        }
        if (value > -1) {
          this.$emit("change", this.options[value].value);
        }
      } else {
        this.$emit("change", value);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
// .uni-input {
//   display: flex;
//   align-items: center;
// }
.picker {
  width: 100%;
}
.select-view {
  display: flex;
  align-items: center;
  justify-content: space-between;

  uni-image {
    width: 2.6rem;
    height: 1.4rem;
    margin-left: 2rem;
  }
}
uni-picker[disabled] {
    cursor: not-allowed;
    background: #eee;
}
</style>